package cn.edu.seu.cose.qol.ws.resource.util;

import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;

import cn.edu.seu.cose.qol.model.dto.exception.ExceptionXmlObject;
import cn.edu.seu.cose.qol.model.dto.message.OperationResult;
import cn.edu.seu.cose.qol.model.dto.message.OperationStatus;


public class OperationResultRepresentationBuilder {
	
	private static OperationResultRepresentationBuilder _instance;
	
	private static final String DEFAULT_ERROR_REPRESENTATION =
			"<operationResult>" +
			"<status>FAILURE</status>" +
			"<exception>" +
			"<type>Unknown</type>" +
			"<message>N/A</message>" +
			"<exception>" +
			"</operationResult>";
	
	public static OperationResultRepresentationBuilder getInstance() {
		if (_instance == null) {
			_instance = new OperationResultRepresentationBuilder();
		}
		
		return _instance;
	}
	
	protected OperationResultRepresentationBuilder() {}
	
	public Representation getOperationResult(boolean successful) {
		OperationStatus status = (successful)
				? OperationStatus.SUCCESS : OperationStatus.FAILURE;
		OperationResult result = new OperationResult(status);
		
		try {
			DomRepresentationBuilder builder =
					DomRepresentationBuilder.getInstance();
			return builder.getRepresentation(result);
		} catch (Exception e) {
			return new StringRepresentation(DEFAULT_ERROR_REPRESENTATION);
		}
	}
	
	public Representation getOperationResult(Exception exception) {
		ExceptionXmlObject exceptionXmlObject = new ExceptionXmlObject(exception);
		OperationResult result = new OperationResult(OperationStatus.FAILURE,
				exceptionXmlObject);
		try {
			DomRepresentationBuilder builder =
					DomRepresentationBuilder.getInstance();
			return builder.getRepresentation(result);
		} catch (Exception e) {
			return new StringRepresentation(DEFAULT_ERROR_REPRESENTATION);
		}
	}

}
